/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.opprua.dss.application;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.opprua.tidy.util.BuildBean;
import org.opprua.tidy.util.XReader;
import org.w3c.dom.Element;

/**
 * TODO: add Java doc
 * 
 * @author Lin Li
 */
public class RStarter {

  private Element[] servdefs;
  private Element[] beandefs;

  public static void main(String[] f) {
    new RStarter(f).generate();
  }

  public static DApplication getApplication(String[] f) {
    return new RStarter(f).getApp();
  }

  private DApplication getApp() {
    DAppReader[] r = new DAppReader[servdefs.length];
    for (int i = 0; i < r.length; i++) {
      r[i] = new DAppReader();
      r[i].basic(servdefs[i]);
      r[i].read(servdefs[i]);
    }
    DApplication application = new DApplication(r);
    application.connect();
    return application;
  }

  private RStarter(String[] f) {
    String[] files = getFiles(f);

    List<Element> servs = new ArrayList<Element>();
    List<Element> beans = new ArrayList<Element>();
    for (int i = 0; i < files.length; i++) {
      Element e = XReader.getDocRoot(files[i]);
      if (e.getTagName().equals("server")) {
        servs.add(e);
      } else if (e.getTagName().equals("beandef")) {
        beans.add(e);
      }
    }
    servdefs = servs.toArray(new Element[servs.size()]);
    beandefs = beans.toArray(new Element[beans.size()]);
  }

  private static String[] getFiles(String[] f) {
    if (f.length != 1) return f;

    File file = new File(f[0]);
    if (!file.isDirectory()) return f;

    String r = f[0];
    if ("\\/".indexOf(r.substring(r.length() - 1)) < 0) {
      r = r + "/";
    }
    String[] files = new File(r).list();
    List<String> fs = new ArrayList<String>();
    for (int i = 0; i < files.length; i++) {
      if (files[i].endsWith(".xml")) fs.add(r + files[i]);
    }
    return fs.toArray(new String[fs.size()]);
  }

  private void generate() {
    for (int i = 0; i < beandefs.length; i++) {
      BuildBean.generate(beandefs[i]);
    }
    DApplication app = getApp();
    String[] p = app.getProviderNames();
    for (int i = 0; i < p.length; i++) {
      app.getProvider(p[i]).generateInterface();
    }
  }
}
